import {
  ForwardedRef,
  forwardRef,
  ReactChild,
  useCallback,
  useEffect,
  useRef,
} from 'react';
import { getMessage } from '@inbiz/react';
import { connect, mapProps, useField } from '@formily/react';
import { useEvents } from '@inbiz/utils';
import { IPageInbiz } from '@inbiz/core/lib/sdk/inbiz';
import cls from 'classnames';
import TableCard from './TableCard';
import InBizTable from './Table';
import { setTableStorage, useInbizPrefixCls, useIsDesigner } from '../../hooks';
import { InBizTableCtx, InBizTableRefCtx } from '../../context';
import TableDesigner from '../../designer/web/designer';
import TableTopBtnGroup from './TableTopBtnGroup';
import TableTopQuery from './TableTopQuery';
import Toolbar from './Toolbar';
import { TablePreviewProps } from '../../interfaces';
import { EventsMap } from '../../shared';
import '../../style.less';

const Table: any = forwardRef(
  (props: TablePreviewProps, ref: ForwardedRef<any>) => {
    const {
      emit,
      callBackEvents,
      tableViewType,
      thumbnail,
      prefixCls = 'table',
      showPageType = 'list',
      zebraEffect,
      controlId = '',
      zebraEffectColor = '',
      tableHeaderColor = '',
      inbiz,
      viewMode
    } = props;
    const filed = useField<{ componentProps: { showPageType: string } }>();
    const tablePrefixCls = useInbizPrefixCls(prefixCls);
    const isDesigner = useIsDesigner();
    const searchRef = useRef({
      pageInfo: {
        pageSize: 30,
        current: 1,
      },
    });
    const firstRequestRef = useRef<boolean>(true);
    const pageRef = useRef<{ page: IPageInbiz }>(null);
    const inbizTableRef = useRef<any>(null);
    // 表格查询区域
    const tableTopRef = useRef<any>(null);
    const [eventsRef] = useEvents(callBackEvents, emit);
    const modalFormRef = useRef(null);
    const storage = localStorage.getItem('inbiz-table');
    const viewType = thumbnail
      ? showPageType === 'list'
        ? 'table'
        : 'card'
      : tableViewType;
    const changeView = useCallback(() => {
      const tableStorage = localStorage.getItem('inbiz-table');
      const guid = inbiz?.appInfo?.userInfo.guid;
      const page = inbiz?.pageId;
      let tableInfo = tableStorage && JSON.parse(tableStorage);
      let type = showPageType;
      const nexTtype = showPageType === 'list' ? 'thumbnail' : 'list';
      (emit as any)?.(EventsMap.onViewClick, nexTtype);
      if (tableInfo?.[guid]?.[page]?.[controlId]?.type) {
        type = tableInfo[guid][page][controlId]?.type;
      }
      setTableStorage({
        inbiz,
        controlId,
        nexTtype,
      });
      if (!thumbnail) {
        return;
      }
      if (type === 'list') {
        filed.componentProps.showPageType = 'thumbnail';
      } else {
        filed.componentProps.showPageType = 'list';
      }
    }, [storage, showPageType]);
    useEffect(() => {
      if (thumbnail && storage && !isDesigner) {
        const info = JSON.parse(storage);
        const userId = inbiz?.appInfo?.userInfo.guid;
        const currentPage = inbiz?.pageId;
        if (
          info[userId] &&
          info[userId][currentPage] &&
          info[userId][currentPage][controlId]
        ) {
          filed.componentProps.showPageType =
            info[userId][currentPage][controlId]?.type ||
            filed.componentProps.showPageType;
        }
      }
    }, [storage]);
    useEffect(() => {
      if (!inbizTableRef?.current) {
        return;
      }
      if (zebraEffectColor) {
        inbizTableRef.current.style?.setProperty(
          '--inbiz-zebra-bg',
          zebraEffectColor,
        );
      }
      if (tableHeaderColor) {
        inbizTableRef.current.style?.setProperty(
          '--inbiz-head-bg',
          tableHeaderColor,
        );
      }
    }, [inbizTableRef]);
    return (
      <div
        className={cls(`${tablePrefixCls}`, { zebra: zebraEffect })}
        id={`${controlId}zebra`}
        ref={inbizTableRef}
      >
        <InBizTableRefCtx.Provider
          value={{
            searchRef,
            eventsRef,
            firstRequestRef,
            modalFormRef,
            pageRef,
            tableTopRef,
            inbizTableRef,
          }}
        >
          <InBizTableCtx.Provider value={{ ...props, changeView,  topBtnMorePopover: props.topBtnMorePopover === 'fold'  }}>
            {isDesigner ? (
              <TableDesigner {...props} ref={ref} />
            ) : viewType === 'table' ? (
              <InBizTable {...props} ref={ref} />
            ) : (
              <TableCard  ref={ref} {...props} />
            )}
          </InBizTableCtx.Provider>
        </InBizTableRefCtx.Provider>
      </div>
    );
  },
);

Table.Query = (props: { children: ReactChild }) => {
  return <TableTopQuery {...props} />;
};

Table.BtnGroup = (props: { children: ReactChild,viewMode:any }) => {
  return <TableTopBtnGroup {...props}  />;
};

Table.Toolbar = () => {
  return <Toolbar />;
};

export default connect(
  Table,
  mapProps({}, (props, field) => {
    const padding = field.decoratorProps?.style?.padding?.split(' ');
    const margin = field.decoratorProps?.style?.margin?.split(' ');
    const { formItems } = props.columnConfig || {};
    if (formItems && formItems?.height) {
      if (!formItems?.maxHeight) {
        formItems['maxHeight'] = {
          height: 60,
          suffix: '%',
        };
      }
      if (!formItems?.minHeight) {
        formItems['minHeight'] = {
          height: 45,
          suffix: '%',
        };
      }
    }
    if (formItems?.actionDisplaySetup) {
      if (!formItems?.tableHeaderBtnShow) {
        formItems['tableHeaderBtnShow'] = formItems.actionDisplaySetup;
      }
      if (!formItems?.inLineBtnShow) {
        formItems['inLineBtnShow'] = formItems.actionDisplaySetup;
      }
    }
    return {
      ...props,
      placeHolder: getMessage(props.placeHolder),
      boxPadding: padding ? parseFloat(padding[0]) + parseFloat(padding[2]) : 0,
      boxMargin: margin ? parseFloat(margin[0]) + parseFloat(margin[2]) : 0,
    };
  }),
);
